package com.mingqijia.gassafety.job.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.HistoryBroken;
import com.mingqijia.gassafety.db.entity.vo.HistoryBrokenVO;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.mapper.HistoryBrokenMapper;
import com.mingqijia.gassafety.job.request.RecordLogRequest;
import com.mingqijia.gassafety.job.response.BrokenLogResponse;
import com.mingqijia.gassafety.job.response.CompanyListResponse;
import com.mingqijia.gassafety.job.response.OrganizationResponse;
import com.mingqijia.gassafety.job.service.*;
import com.mingqijia.gassafety.job.response.*;
import com.mingqijia.gassafety.job.service.CompanyService;
import com.mingqijia.gassafety.job.service.ConsumerService;
import com.mingqijia.gassafety.job.service.EquipmentService;
import com.mingqijia.gassafety.job.service.HistoryBrokenService;
import com.mingqijia.gassafety.job.service.OrganizationService;
import com.mingqijia.gassafety.job.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 报警器设备故障记录 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-08-08
 */
@Service
@Slf4j
public class HistoryBrokenServiceImpl extends ServiceImpl<HistoryBrokenMapper, HistoryBroken> implements HistoryBrokenService {
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    InfluxDBConfiguration influxDBConfiguration;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    HeaderUtil headerUtil;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    CompanyService companyService;
    @Autowired
    private UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    public PageUtil<BrokenLogResponse> getList(RecordLogRequest req) {

        List<BrokenLogResponse> resultList = new ArrayList<>();
        LatestLogListVO vo = new LatestLogListVO();
        BeanUtils.copyProperties(req, vo);

        //1.1所属组织
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(req.getSpId()) && !spId.equals(req.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(req.getSpId());
        }
        vo.setSpIds(spIds);

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());

        Page<HistoryBrokenVO> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryBrokenVO> list = new ArrayList<>();
        //页面不完全返回结果封装
        if (req.getTemplateType() == null) {
            req.setTemplateType(headerUtil.getTemplateType());
        }
        if (TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()) {
            list = baseMapper.getVccRecord(vo);
        } else if (TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            list = baseMapper.getAsstRecord(vo);
        }
        log.info("getList-list:{}", JSONObject.toJSONString(list));
        //查询组织架构名称
        List<CompanyListResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyListResponse::getSpId, CompanyListResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型列表
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE);
            //行业类型列表
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商名称
            ConsoleSkSupplierListResponse listResponse = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", listResponse);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (listResponse != null && listResponse.getCode() == 0 && listResponse.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(listResponse.getData())) {
                supplierListVos = listResponse.getData();
            }
            //运营商列表
            List<DictionaryItemRespDTO> operatorList = holder.getDictionaryByKey(Constants.OPERATOR_CODE);
            //组织名称列表
            List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());

            for (HistoryBrokenVO historyBrokenVO : list) {
                BrokenLogResponse response = new BrokenLogResponse();
                BeanUtils.copyProperties(historyBrokenVO, response);
                historyBrokenVO.setConsumerId(response.getConsumerId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyBrokenVO.getOrgCode()) && orgSubsCodeMap.containsKey(historyBrokenVO.getOrgCode())) {
                    response.setCompanyName(orgSubsCodeMap.get(historyBrokenVO.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyBrokenVO.getSpId())) {
                        response.setCompanyName(companyNameMap.get(historyBrokenVO.getSpId()));
                    }
                }
                //处理人信息
                if (!StringUtils.isEmpty(historyBrokenVO.getUserName()) && !StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserName() + "(" + historyBrokenVO.getUserAccount() + ")");
                } else if (StringUtils.isEmpty(historyBrokenVO.getUserName()) && !StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserAccount());
                } else if (!StringUtils.isEmpty(historyBrokenVO.getUserName()) && StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserName());
                }
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyBrokenVO.getAppealStatus()).getMsg());
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyBrokenVO.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyBrokenVO.getIndustryType()));
                //设置设备厂商
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        historyBrokenVO.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    response.setEquipmentManufacturer(listVos.get(0).getMsName());
                }
                //紫荆设备 故障原因、联系人手机号
                //运营商
                response.setOperators(getName(operatorList, historyBrokenVO.getOperators()));
                //紫荆设备 故障原因、联系人手机号
                if (historyBrokenVO.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
                    if (!StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenReason() + ";" + historyBrokenVO.getBrokenInfo());

                    } else if (StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenInfo());
                    }
                    response.setContactPhone(historyBrokenVO.getPhone());
                }
                //所属组织
                if (!CollectionUtils.isEmpty(organizationList)) {
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(historyBrokenVO.getSpId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        response.setSpName(collect.get(0).getSpName());
                    }
                }
                if (!StringUtils.isEmpty(historyBrokenVO.getAppealResult()) || historyBrokenVO.getAppealTime() != null) {
                    String dateString = "";
                    if (historyBrokenVO.getAppealTime() != null) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        dateString = dateFormat.format(historyBrokenVO.getAppealTime());
                    }
                    response.setAppealResult(historyBrokenVO.getAppealResult()+dateString);
                }
                //设备是否携带电磁阀
                response.setHasValve(historyBrokenVO.getValveInfoId() == 0 ? "-":"有");
                resultList.add(response);
            }
        }

        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList);
        return pageInfo;
    }

    @Override
    public void brokenLogUpdate(String param) {

        Long totalRows = this.baseMapper.getTotalRows();

        int batchSize = Integer.parseInt(param);
        // 初始化批次号
        int batchNumber = 0;

        // 计算需要执行的批次数
        int totalBatches = (int) Math.ceil((double) totalRows / batchSize);

        while (batchNumber < totalBatches){
            batchNumber = batchNumber + 1;
            // 计算当前批次的起始行数
            Integer startRow = (batchNumber - 1) * batchSize;
            log.info("批次{}更新开始", batchNumber);
            this.baseMapper.batchUpdate(startRow, batchSize);
            log.info("批次{}更新成功", batchNumber);
        }

    }


    private String getName(List<DictionaryItemRespDTO> list, String value) {
        if (!CollectionUtils.isEmpty(list)) {
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)) {
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

}
